<?php
class Http_Server {
	protected static $instance;
	public $app;

	public static $server;
	public static $header;
	public static $get;
	public static $post;
	public static $request;
	public static $cookie;
	public static $files;

	public function __construct() {
		$this->app = new Yaf_Application(APP_PATH . '/conf/application.ini');
		$config = Yaf_Application::app()->getConfig();

		$http = new \Swoole\Http\Server($config->swoole->host, $config->swoole->port);
		$http->set(
			[
				'daemonize' => $config->swoole->daemonize,
				'worker_num' => $config->swoole->worker_num,
				'max_request' => $config->swoole->max_request,
	            'dispatch_mode' => $config->swoole->dispatch_mode
			]
		);
		
		$http->on('WorkerStart' , [$this, 'onWorkerStart']);

		$http->on('request', new Session_Middleware(function($request, $response) {
			$response->header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Keep-Alive, User-Agent, Cookie, Token, Authorization, Cache-Control');
        	$response->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS');
        	$response->header('Access-Control-Allow-Origin', '*');
			$response->header('Access-Control-Allow-Credentials', true);
			$response->header('Content-Type', 'text/html; charset=utf-8');
			
			self::$server = $request->server ?? [];
			self::$header = $request->header ?? [];
			self::$get = $request->get ?? [];
			self::$post = $request->post ?? [];
			self::$cookie = $request->cookie ?? [];
			self::$files = $request->files ?? [];
			self::$request = array_merge(self::$get, self::$post);
			
			ob_start();
			try {
				Yaf_Dispatcher::getInstance()->autoRender(FALSE);
				$yafRequest = new Yaf_Request_Http(self::$server['request_uri']);
				Yaf_Registry::set('Yaf_Request', $yafRequest);
			    $this->app->getDispatcher()->dispatch($yafRequest);
			} catch (Yaf_Exception $e) {
				// TODO
			}
		    $result = ob_get_contents();
		  	ob_end_clean();
		  	$response->end($result);
		}));

		$http->start();
	}

	public function onWorkerStart($server, $workerId) {
		Yaf_Loader::import(APP_PATH . '/library/Helper.php');
		Yaf_Loader::import(APP_PATH . '/vendor/autoload.php');
		ob_start();
		$this->app->bootstrap()->run();
		if ($workerId == 0) {
			Crontab::start();
		}
		ob_end_clean();
	}
	
	public static function getInstance() {
		if (!self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
	}
}
